import 'dart:convert';

import 'package:crypto/crypto.dart';
import 'package:archive/archive.dart';
import 'package:archive/archive_io.dart';
import 'package:vischat/core/config/app_config.dart';

/// 客户端获取userSig，测试用，实际最好放在服务端
class GenerateTestUserSig {
  GenerateTestUserSig._();

  static final String _key = AppConfig.tencent_key;
  static final int _sdkAppId = AppConfig.tencent_sdkAppId;

  /// Generate UserSig
  ///
  static String genSig({
    required String userId,
    int expire = 30 * 24 * 60 * 60,
  }) {
    int currTime = _getCurrentTime();
    String sig = '';
    Map<String, dynamic> sigDoc = <String, dynamic>{};
    sigDoc.addAll({
      "TLS.ver": "2.0",
      "TLS.identifier": userId,
      "TLS.sdkappid": _sdkAppId,
      "TLS.expire": expire,
      "TLS.time": currTime,
    });

    sig = _hMacSha256(identifier: userId, currTime: currTime, expire: expire);
    sigDoc['TLS.sig'] = sig;
    String jsonStr = json.encode(sigDoc);
    List<int>? compress = const ZLibEncoder().encode(utf8.encode(jsonStr));
    return _escape(content: base64.encode(compress));
  }

  static int _getCurrentTime() {
    return (DateTime.now().millisecondsSinceEpoch / 1000).floor();
  }

  static String _hMacSha256({
    required String identifier,
    required int currTime,
    int expire = 30 * 24 * 60 * 60,
  }) {
    int sdkAppId = _sdkAppId;
    String contentToBeSigned =
        "TLS.identifier:$identifier\nTLS.sdkappid:$sdkAppId\nTLS.time:$currTime\nTLS.expire:$expire\n";
    Hmac hMacSha256 = Hmac(sha256, utf8.encode(_key));
    Digest hMacSha256Digest = hMacSha256.convert(
      utf8.encode(contentToBeSigned),
    );
    return base64.encode(hMacSha256Digest.bytes);
  }

  static String _escape({required String content}) {
    return content
        .replaceAll('+', '*')
        .replaceAll('/', '-')
        .replaceAll('=', '_');
  }
}
